package freespiritsocial.io.user.ui.fragment.message

import android.os.Bundle
import androidx.core.os.bundleOf
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import com.sendbird.android.BaseChannel
import com.sendbird.android.BaseMessage
import com.sendbird.android.GroupChannel
import com.sendbird.android.SendBird
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgMessageBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.hideSoftKeyboard
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ext.loadListData
import freespiritsocial.io.user.ext.setOnSearchBtnClick
import freespiritsocial.io.user.ui.adapter.MessageAdapter
import freespiritsocial.io.user.ui.fragment.mine.MineFrg
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.MessageViewModel
import freespiritsocial.io.user.weight.SwipeItemLayout
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @description 消息页
 */
class MessageFrg: BaseFragment<MessageViewModel,FrgMessageBinding>() {
    private val userInfo by lazy(LazyThreadSafetyMode.NONE) {
        CacheUtil.getUser()
    }

    val adapter by lazy(LazyThreadSafetyMode.NONE) {
        MessageAdapter().apply {
            addChildClickViewIds(R.id.iv_avatar,R.id.del,R.id.host)
            setOnItemChildClickListener { _,view,position ->
                when (view.id) {
                    R.id.del -> {
                        data[position].markAsRead {
                            SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                                eventViewModel.hasUnReadMessage.postValue(i != 0)
                            }
                        }
                        data[position].hide(true,null)
                        removeAt(position)
                    }
                    R.id.iv_avatar -> {
                        val groupChannel = data[position]
                        val member = groupChannel.members.find { it.userId != userInfo?.resourceId } ?: return@setOnItemChildClickListener
                        goToPeopleHome(member.metaData["userId"])
                    }
                    R.id.host -> {
                        val groupChannel = data[position]
                        val nickname = groupChannel.members.find { it.userId != userInfo?.resourceId }?.nickname ?: ""
                        nav().navigateAction(
                            R.id.chatFrag,
                            bundleOf(ChatFrag.EXTRA_GROUP_CHANNEL_URL to groupChannel.url,ChatFrag.EXTRA_GROUP_CHANNEL_NAME to nickname)
                        )
                    }
                }
            }
        }
    }

    private fun goToPeopleHome(id: String?) {
        mViewModel.getUserInfo(id) {
            nav().navigateAction(R.id.mineFrg,bundleOf(MineFrg.KEY_IS_USER to false,MineFrg.KEY_USER to it))
        }
    }

    override fun layoutId(): Int = R.layout.frg_message

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        model = mViewModel
        click = Click()
        recyclerView.init(adapter,emptyText = "No chat history.",emptyImage = R.mipmap.empty_comments).also {
            it.addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(context))
        }.addItemDecoration(
            SpaceItemDecoration(
                dp2px(20f),
                dp2px(15f)
            )
        )
        etSearch.setOnSearchBtnClick {
            hideSoftKeyboard(requireActivity())
            mViewModel.getChatList(true)
        }
    }

    override fun dismissLoading() {
        super.dismissLoading()
        mDatabind.refresh.finishRefresh()
        mDatabind.refresh.finishLoadMore()
    }

    override fun createObserver() {
        super.createObserver()
        SendBird.addChannelHandler(userInfo?.resourceId,object: SendBird.ChannelHandler() {
            override fun onMessageReceived(baseChannel: BaseChannel,baseMessage: BaseMessage) {
                SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                    eventViewModel.hasUnReadMessage.postValue(i != 0)
                }
                eventViewModel.messageReceivedEvent.postValue(baseChannel to baseMessage)
            }

            override fun onMessageDeleted(baseChannel: BaseChannel,msgId: Long) {
                super.onMessageDeleted(baseChannel,msgId)
                SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                    eventViewModel.hasUnReadMessage.postValue(i != 0)
                }
                eventViewModel.messageDelEvent.postValue(baseChannel to msgId)
            }

            override fun onMessageUpdated(channel: BaseChannel,message: BaseMessage) {
                super.onMessageUpdated(channel,message)
                SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                    eventViewModel.hasUnReadMessage.postValue(i != 0)
                }
                eventViewModel.messageUpdatedEvent.postValue(channel to message)
            }

            override fun onChannelChanged(channel: BaseChannel?) = with(channel) {
                SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                    eventViewModel.hasUnReadMessage.postValue(i != 0)
                }
                adapter.data.forEach {
                    if (it.url == this?.url) {
                        adapter.remove(it)
                        adapter.data.add(0,this as? GroupChannel ?: return@with)
                        adapter.notifyDataSetChanged()
                        return@with
                    }
                }
                adapter.data.add(0,this as? GroupChannel ?: return@with)
                adapter.notifyDataSetChanged()
            }

        })
        mViewModel.channelResult.observe(this) {
            loadListData(it,adapter,mDatabind.refresh)
        }
    }

    override fun onStart() {
        super.onStart()
        appViewModel.chatConnectStatus.observe(this) { success ->
            if (!success) return@observe
            mViewModel.getChatList(true)
            SendBird.getTotalUnreadChannelCount { i,sendBirdException ->
                eventViewModel.hasUnReadMessage.postValue(i != 0)
            }
        }
    }

    override fun onStop() {
        super.onStop()
        appViewModel.chatConnectStatus.removeObservers(this)
    }

    override fun lazyLoadData() {
    }

    inner class Click {
        fun createMessage() {
            hideSoftKeyboard(mDatabind.etSearch)
            SendMessageListDialogFragment.crate(this@MessageFrg).show(childFragmentManager,"message")
        }

        fun removeSearch() {
            mViewModel.searchText.set("")
            mViewModel.getChatList(true)
        }

        fun onRefresh() {
            mViewModel.getChatList(true)
        }

        fun onLoadMore() {
            mViewModel.getChatList()
        }
    }
}